'''
Author: cw
Date: 2025-07-22
Description: ...
'''
from sqlalchemy import select

from fapi import ServiceError

from models.mysql_model import Tests, AppTest
from utils import db_util


async def get_list(appid: str):
    """list"""
    condition = [
        AppTest.appid == appid,
        AppTest.is_deleted == 0
    ]
    async with db_util.session_context() as session:
        cursor = (await session.execute(
            select(
                AppTest
            ).filter(
                *condition
            )
        )).scalars()

        test_ids = [
            item.test_id for item in cursor
        ]
        if not test_ids:
            raise ServiceError('尚未配置测试')

        tests_cursor = (await session.execute(
            select(
                Tests
            ).filter(
                Tests.id.in_(test_ids),
                Tests.is_deleted == 0
            ).order_by(Tests.id)
        )).scalars()
        return [
            item.to_dict() for item in tests_cursor
        ]


async def get(test_id: int):
    '''info'''
    condition = [
        Tests.id == int(test_id),
        Tests.is_deleted == 0
    ]
    async with db_util.session_context() as session:
        cursor = (await session.execute(
            select(
                Tests
            ).filter(
                *condition
            )
        )).scalar()
        return cursor.to_dict() if cursor else None


async def get_by_appid(appid: str, offset: int = 0) -> dict:
    """通过偏移量来获取测试"""
    async with db_util.session_context() as session:
        res = (await session.execute(
            select(AppTest).where(
                AppTest.appid == appid,
                AppTest.is_deleted == 0
            ).order_by(AppTest.test_id).offset(offset)
        )).scalar()
        return await get(res.test_id) if res else None
